package com.lk.cofig;

import com.lk.util.JsonUtil;
import com.lk.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;
import java.io.PrintWriter;

/**
 * 资源服务器
 *
 * @author : com.com.lk
 * @date 2021/11/23 14:05
 **/
@EnableResourceServer
@Configuration
public class ResourceAuthorized extends ResourceServerConfigurerAdapter {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private TokenStore tokenStore;

    @Bean
    public TokenStore jdbcTokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("product_api")//指定当前资源的id，非常重要！必须写！
                .tokenStore(tokenStore);//指定保存token的方式
    }
    @Autowired
    private SecurityIgnoreConfig securityIgnoreConfig;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(securityIgnoreConfig.getIgnore()).permitAll() // 白名单
                .anyRequest().authenticated()
                .and()
                .headers().addHeaderWriter((request, response) -> {
            response.addHeader("Access-Control-Allow-Origin", "*");//允许跨域
            if (request.getMethod().equals("OPTIONS")) {//如果是跨域的预检请求，则原封不动向下传达请求头信息
                response.setHeader("Access-Control-Allow-Methods", request.getHeader("Access-Control-Request-Method"));
                response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
            }
        });
        http.exceptionHandling()
                .accessDeniedHandler((request, response, accessDeniedException) -> {
                    Result<Object> of = Result.of(403, "访问拒绝", null);
                    response.setHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(JsonUtil.jsonObjToString(of));
                }).authenticationEntryPoint((request, response, authException) -> {
            Result<Object> of = Result.of(401, "未认证", null);
            response.setHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JsonUtil.jsonObjToString(of));
        });


    }
}
